import * as Cesium from "cesium";
/**
 * 加载模型

 */
export function useLoadLocalModel() {
  function loadModelByEntity() {}

  // scene 加载 
  async function loadModelByScene(
    viewer,
    url,
    longitude,
    latitude,
    height,
    heading,
    pitch,
    roll
  ) {
    // 如果不传，设置默认值
    longitude = Cesium.defaultValue(longitude, 0.0);
    latitude = Cesium.defaultValue(latitude, 0.0);
    height = Cesium.defaultValue(height, 0.0);
    heading = Cesium.defaultValue(heading, 0.0);
    pitch = Cesium.defaultValue(pitch, 0.0);
    roll = Cesium.defaultValue(roll, 0.0);

    // 经纬度转笛卡尔坐标
    const position = Cesium.Cartesian3.fromDegrees(longitude, latitude, height);
    console.log("position", position);
    // 欧拉角
    const hrp = new Cesium.HeadingPitchRoll(heading, pitch, roll);
    // 方位矩阵4
    const modelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(
      position,
      hrp
    );
    console.log("modelMatrix", modelMatrix);
    // 场景
    const model = await Cesium.Model.fromGltfAsync({
      url: url,
      modelMatrix: modelMatrix,
      minimumPixelSize: 128, // 模型的最小像素
    });
    const scene = viewer.scene;
    const camera = viewer.camera;
    scene.primitives.add(model);

    // 模型加载后完成的事件
    model.readyEvent.addEventListener(() => {
      console.log("模型加载完成");
      model.color = Cesium.Color.RED.withAlpha(0.5); // 修改颜色
      model.silhouetteColor = Cesium.Color.RED; // 轮廓折线颜色
      model.silhouetteSize = 2; // 轮廓折线宽度
      //   viewer.camera.lookAt(model);
      // 设置一个动画，但是这个模型不能动
      model.activeAnimations.addAll({
        multiplier: 0.5,
        loop: Cesium.ModelAnimationLoop.REPEAT,
      });

      // 事件系统
      const controller = scene.screenSpaceCameraController;
      const r =
        2.0 * Math.max(model.boundingSphere.radius, camera.frustum.near);
      // 最小  
      controller.minimumZoomDistance = r * 0.5; // 最小的缩放位置

      const center = model.boundingSphere.center;
      const heading = Cesium.Math.toRadians(230.0);
      const pitch = Cesium.Math.toRadians(-20.0);

      camera.lookAt(
        center,
        // 计算偏移量    
        new Cesium.HeadingPitchRange(heading, pitch, r * 2.0)
      );
    });
  }

  return {
    loadModelByEntity,
    loadModelByScene,
  };
}
